<template>
  <view class="page-container">
    <!-- 页面头部 -->
    <PageHeader title="编辑招聘信息" :showBack="true"/>

  <view class="factory-recruitment">
    <view class="post-form">
      <!-- <view class="form-group">
        <text class="label">招聘类型 <text class="required">*</text></text>
        <view class="radio-group">
          <label class="radio-item" @click="recruitmentType = 0">
            <view class="radio-inner">
              <view
                  class="radio-circle"
                  :class="{ checked: recruitmentType === 0 }"
              >
                <view class="radio-dot" v-if="recruitmentType === 0"></view>
              </view>
              <text class="radio-text">普通招聘</text>
            </view>
          </label>

          <label class="radio-item" @click="recruitmentType = 1">
            <view class="radio-inner">
              <view
                  class="radio-circle"
                  :class="{ checked: recruitmentType === 1 }"
              >
                <view class="radio-dot" v-if="recruitmentType === 1"></view>
              </view>
              <text class="radio-text">特殊招聘</text>
            </view>
          </label>
        </view>
        <text v-if="formErrors.recruitType" class="error-text">{{
            formErrors.recruitType
          }}</text>
      </view> -->
      <view class="form-group">
        <text class="label">职位名称 <text class="required">*</text></text>
        <input
            type="text"
            v-model="formData.positionName"
            class="input"
            :class="{ 'error-border': formErrors.positionName }"
            placeholder="请输入职位名称"
        />
        <text v-if="formErrors.positionName" class="error-text">{{
            formErrors.positionName
          }}</text>
      </view>

      <!-- 职位类型输入框 -->
      <view class="form-group">
        <text class="label">职位类型</text>
        <view
            class="picker-input"
            :class="{ 'error-border': formErrors.type }"
            @click="showTypePicker = true"
        >
          <text class="picker-text">{{ pickerTitle || currentInfo.type }}</text>
        </view>
        <text v-if="formErrors.type" class="error-text">{{
            formErrors.type
          }}</text>
      </view>

      <view class="form-group">
        <text class="label">公司名称 <text class="required">*</text></text>
        <input
            type="text"
            v-model="formData.corporateName"
            class="input"
            :class="{ 'error-border': formErrors.corporateName }"
            placeholder="请输入公司名称"
        />
        <text v-if="formErrors.corporateName" class="error-text">{{
            formErrors.corporateName
          }}</text>
      </view>

      <view class="form-group">
        <text class="label">工作地点 <text class="required">*</text></text>
        <input
            type="text"
            v-model="formData.location"
            class="input"
            :class="{ 'error-border': formErrors.location }"
            placeholder="请输入工作地点"
        />
        <text v-if="formErrors.location" class="error-text">{{
            formErrors.location
          }}</text>
      </view>

      <view class="form-group">
        <text class="label">经验要求 <text class="required">*</text></text>
        <input
            type="text"
            v-model="formData.experience"
            class="input"
            :class="{ 'error-border': formErrors.experience }"
            placeholder="请输入经验要求"
        />
        <text v-if="formErrors.experience" class="error-text">{{
            formErrors.experience
          }}</text>
      </view>

      <view class="form-group">
        <text class="label">薪资范围 <text class="required">*</text></text>
        <view class="salary-input flex items-center">
          <input
              type="number"
              v-model="formData.salaryMin"
              class="input flex-1"
              :class="{
              'error-border': formErrors.salaryMin || formErrors.salaryRange,
            }"
              placeholder="最低薪资"
          />
          <text class="mx-[24rpx] text-[24rpx]">至</text>
          <input
              type="number"
              v-model="formData.salaryMax"
              class="input flex-1"
              :class="{
              'error-border': formErrors.salaryMax || formErrors.salaryRange,
            }"
              placeholder="最高薪资"
          />
          <text class="ml-[24rpx] text-[24rpx]">/月</text>
        </view>
        <text v-if="formErrors.salaryMin" class="error-text">{{
            formErrors.salaryMin
          }}</text>
        <text v-if="formErrors.salaryMax" class="error-text">{{
            formErrors.salaryMax
          }}</text>
        <text v-if="formErrors.salaryRange" class="error-text">{{
            formErrors.salaryRange
          }}</text>
      </view>

      <!-- <view class="form-group">
        <text class="label">职位标签</text>
        <view class="tags-container flex flex-wrap gap-[20rpx]">
          <view
            v-for="(tag, index) in tags"
            :key="index"
            :class="['tag-option', { selected: tag.selected }]"
            @click="toggleTag(index)"
          >
            {{ tag.name }}
          </view>
        </view>
      </view> -->
      <view class="mb-[40rpx]">
        <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
        >职位标签</text
        >

        <!-- 添加技能 -->
        <view class="flex mb-[24rpx]">
          <nut-input
              v-model="newSkill"
              placeholder="输入标签后点击添加"
              class="flex-1 rounded-l-[15rpx] border-2 border-gray-200 p-[20rpx] text-[28rpx] bg-gray-50"
              @keypress="onSkillKeyPress"
          />
          <nut-button
              type="primary"
              class="rounded-r-[15rpx] text-[28rpx] bg-blue-600 border-none h-[84rpx] px-[30rpx]"
              @click="addSkill"
          >
            添加
          </nut-button>
        </view>

        <!-- 显示标签 -->
        <view class="flex flex-wrap gap-[16rpx]">
          <view
              v-for="(tag, index) in currentInfo.labels"
              :key="index"
              class="flex items-center bg-blue-50 text-blue-600 px-[20rpx] py-[12rpx] rounded-[30rpx] text-[26rpx] border border-blue-100"
          >
            <text>{{ tag }}</text>
            <IconFont
                name="close"
                size="10"
                class="ml-[12rpx] text-[24rpx] text-blue-400 cursor-pointer"
                @click="removeSkill(index)"
            />
          </view>
        </view>
      </view>

      <view class="form-group">
        <text class="label">职位描述 <text class="required">*</text></text>
        <nut-textarea
            v-model="formData.description"
            class="textarea"
            :class="{ 'error-border': formErrors.description }"
            placeholder="请输入职位描述"
        />
        <text v-if="formErrors.description" class="error-text">{{
            formErrors.description
          }}</text>
      </view>

      <!-- 状态更改 -->
      <!-- <view class="form-group">
        <text class="label">招聘状态</text>
        <view
            class="picker-input"
            :class="{ 'error-border': formErrors.status }"
            @click="showStatusPicker = true"
        >
          <text class="picker-text">{{ statusText || '请选择招聘状态' }}</text>
        </view>
        <text v-if="formErrors.status" class="error-text">{{ formErrors.status }}</text>
      </view> -->

      <nut-button class="submit-btn" @click="submitForm">保存编辑</nut-button>
    </view>
    <!-- 职位类型选择器弹窗 -->
    <nut-popup v-model:visible="showTypePicker" position="bottom" round>
      <nut-picker
          :columns="jobTypes.map((item) => ({ text: item.type, value: item.id }))"
          :title="pickerTitle"
          @confirm="onTypeConfirm"
          @cancel="showTypePicker = false"
      />
    </nut-popup>

    <nut-popup v-model:visible="showStatusPicker" position="bottom" round>
      <nut-picker
          :columns="statusOptions.map(exp => ({text: exp, value: exp}))"
          title="选择岗位状态"
          @confirm="onStatusConfirm"
          @cancel="showStatusPicker = false"
      />
    </nut-popup>

  </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { showToast } from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post } from "@/utils/request";
import Taro from "@tarojs/taro";
import PageHeader from "@/components/PageHeader.vue";
import {getCurrentInstance} from "@tarojs/runtime";


const statusOptions = [
  '招聘中', '停止招聘'
]

const currentInfo = ref<any>({})

export interface JobPost {
  id?:string;
  corporateName?: string;
  deadline?: string;
  description?: string;
  experience?: string;
  location?: string;
  positionName?: string;
  salaryMax?: string;
  salaryMin?: string;
  type?: number;
  labels?: string;
  [property: string]: any;
  update_time?:string;
  status?:number
}

// 表单数据
const formData = reactive<JobPost>({});
const recruitmentType = ref(0); // 添加招聘类型字段
const showStatusPicker = ref(false)
const statusText = ref("")

//获取路由参数的‘id’
const courseId = getCurrentInstance()
const id = courseId.router?.params.id as string || ""
formData.id = id
console.log("id",id)

/** 表单数据类型 - 仅保留职位类型相关字段 */
interface JobFormData {
  id: number;
  type: string;
}

/** 职位类型选项 */
// const jobTypes = ["普工", "技工", "管理", "质检", "仓储", "后勤", "其他"];
const jobTypes = ref<JobFormData[]>([]);

/** 职位类型选择器显示状态 */
const showTypePicker = ref(false);
const pickerTitle = ref();

/** 职位类型选择器确认事件 */
function onTypeConfirm(value: any) {
  // 将选择的职位类型赋值给表单
  formData.type = value?.selectedValue[0] || "";
  console.log(formData.type);
  // 更新标题（可选）
  const selectedType = jobTypes.value.find((item) => item.id === formData.type);
  pickerTitle.value = selectedType?.type || "选择职位类型";
  // 关闭弹窗
  showTypePicker.value = false;
}

// 计算属性：根据 id 获取 type 名称
// const typeName = computed(() => {
//   const selectedType = jobTypes.value.find(item => item.id == formData.type);
//   console.log(selectedType?.type)
//   return selectedType?.type || '请选择职位类型';
// })

// 职位标签
const tags = ref([]);

const newSkill = ref([]);
function onSkillKeyPress(e: any) {
  if (e.key === "Enter") {
    addSkill();
  }
}
function addSkill() {
  const skill = newSkill.value.trim();
  if (skill && !tags.value.includes(skill)) {
    tags.value.push(skill);
    newSkill.value = "";
  }
}

function removeSkill(index: number) {
  tags.value.splice(index, 1);
}

// 选中的标签
// const selectedTags = ref<string[]>([]);

// 切换标签选择状态
// const toggleTag = (index: number) => {
//   tags.value[index].selected = !tags.value[index].selected;
//   // 更新选中的标签列表
//   selectedTags.value = tags.value
//     .filter((tag) => tag.selected)
//     .map((tag) => tag.name);
// };

// 表单验证错误信息
const formErrors = reactive<
    Partial<Record<keyof JobPost | "salaryRange", string>>
>({});

// 表单验证方法
const validateForm = (): boolean => {
  const errors: Partial<Record<keyof JobPost | "salaryRange", string>> = {};

  // if (!formData.recruitmentType) {
  //   errors.recruitmentType = "请选择招聘类型";
  // }

  // 职位名称验证
  if (!formData.positionName?.trim()) {
    errors.positionName = "请输入职位名称";
  }

  // 公司名称验证
  if (!formData.corporateName?.trim()) {
    errors.corporateName = "请输入公司名称";
  }

  if (!formData.type) {
    errors.type = "请选择职位类型";
  }

  // 工作地点验证
  if (!formData.location?.trim()) {
    errors.location = "请输入工作地点";
  }

  // 经验要求验证
  if (!formData.experience?.trim()) {
    errors.experience = "请输入经验要求";
  }

  // 最低薪资验证
  if (!formData.salaryMin?.trim()) {
    errors.salaryMin = "请输入最低薪资";
  } else if (isNaN(Number(formData.salaryMin))) {
    errors.salaryMin = "最低薪资必须为数字";
  }

  // 最高薪资验证
  if (!formData.salaryMax?.trim()) {
    errors.salaryMax = "请输入最高薪资";
  } else if (isNaN(Number(formData.salaryMax))) {
    errors.salaryMax = "最高薪资必须为数字";
  }

  // 薪资范围验证（当两者都填写时）
  if (
      formData.salaryMin &&
      formData.salaryMax &&
      !errors.salaryMin &&
      !errors.salaryMax
  ) {
    const min = Number(formData.salaryMin);
    const max = Number(formData.salaryMax);
    if (min >= max) {
      errors.salaryRange = "最低薪资必须小于最高薪资";
    }
  }

  // 职位描述验证
  if (!formData.description?.trim()) {
    errors.description = "请输入职位描述";
  }

  // 更新错误信息
  Object.assign(formErrors, errors);

  // 返回验证结果（无错误则为有效）
  return Object.keys(errors).length === 0;
};

//进行状态的更改
function onStatusConfirm(value: any) {
  console.log("选项",value.selectedValue[0])
  if(value?.selectedValue[0] === "招聘中"){
    //console.log("进入")
    statusText.value = "招聘中"
    formData.status = 1
  }
  else {
    statusText.value = "停止招聘"
    formData.status = 2
  }
  showStatusPicker.value = false
}


// 提交表单
const submitForm = async () => {

  // 生成当前时间，格式：YYYY - MM - DD HH:mm:ss
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  formData.update_time = formattedTime


  // 先进行表单验证
  if (!validateForm()) {
    showToast({ title: "请完善必填信息", icon: "none", duration: 2000 });
    return;
  }

  // 显示加载状态
  Taro.showLoading({ title: "发布中..." });

  try {
    // 构建提交数据（包含选中的标签）
    const submitData = {
      ...formData,

      recruitmentType: recruitmentType.value,
      labels: tags.value.join(","),
    };
    console.log("====>", submitData);
    // 提交数据到接口
    const res = await post("/recruitment/save", submitData);
    console.log("====>", res);
    if (res.code === 0) {
      Taro.showToast({ title: "发布成功", icon: "success", duration: 2000 });
      // 重置表单
      Object.keys(formData).forEach((key) => {
        formData[key as keyof JobPost] = "";
      });
      // tags.value.forEach((tag) => (tag.selected = false));
      tags.value = [];
      //跳转页面
      Taro.redirectTo({
        url:'/pages/post/my-publish'
      })
    } else {
      Taro.showToast({ title: res.msg || "发布失败", icon: "none", duration: 2000 });
    }
  } catch (error) {
    Taro.showToast({ title: "网络错误，请稍后重试", icon: "none", duration: 2000 });
  } finally {
    // 隐藏加载状态
    Taro.hideLoading();
  }
};

// 招聘类型
const jobRecruitmentType = async () => {
  const res = await post("/dictionary/recruitmentType");
  if (res.code == "0") {
    jobTypes.value = res.data.map((item: any) => ({
      id: item.columns.id,
      type: item.columns.name,
    }));
  }
};
jobRecruitmentType();

//通过id获取当前修改的订单数据
const detail = async ()=>{
  const res = await post("/recruitment/getById",{id:formData.id});
  if(res.code == "0"){
    currentInfo.value = res.data.columns
    console.log("current当前数据",currentInfo.value)
    
    // 将获取的数据赋值给表单
    formData.location = currentInfo.value.location || '';
    formData.experience = currentInfo.value.experience || '';
    formData.salaryMin = currentInfo.value.salary_min || '';
    formData.salaryMax = currentInfo.value.salary_max || '';
    formData.description = currentInfo.value.description || '';
    formData.corporateName = currentInfo.value.corporate_name || '';
    formData.positionName = currentInfo.value.position_name || '';
    formData.type = currentInfo.value.type || '';
    
    pickerTitle.value = jobTypes.value.find((item) => item.id === currentInfo.value.type)?.type
    if(currentInfo.value.status === 1){
      //console.log("进入")
      statusText.value = "招聘中"
      formData.status = 1
    }
    else {
      statusText.value = "停止招聘"
      formData.status = 2
    }
  }
}
detail();

</script>

<style>
.post-form {
  background-color: white;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #555;
  font-size: 28rpx;
}

.required {
  color: #ff4d4f;
}

.input,
.textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

/* 错误状态样式 */
.error-border {
  border-color: #ff4d4f !important;
}

.error-text {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 8rpx;
  display: block;
  line-height: 1.4;
}

.salary-input {
  display: flex;
  align-items: center;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag-option {
  background-color: #f0f0f0;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  cursor: pointer;
  font-size: 24rpx;
  transition: all 0.2s;
}

.tag-option.selected {
  background-color: #e3f2fd;
  color: #1976d2;
  border-color: #1976d2;
  border: 1rpx solid;
}

.submit-btn {
  background-color: #1976d2 !important;
  color: white !important;
  width: 100%;
  margin-top: 40rpx;
  padding: 24rpx 40rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
}

.preview {
  margin-top: 40rpx;
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.container {
  width: 750rpx;
  max-width: 100%;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  margin-bottom: 40rpx;
  height: 60rpx;
}

.header h1 {
  color: #333;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.salary-input span {
  margin: 0 24rpx;
}

.preview-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #eee;
}

.job-card {
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 30rpx;
  position: relative;
}

.job-card::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 4rpx;
  background-color: #1976d2;
  border-radius: 12rpx 0 0 12rpx;
}

.job-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.company-info {
  color: #666;
  font-size: 24rpx;
  margin-bottom: 10rpx;
}

.salary {
  color: #f44336;
  font-size: 32rpx;
  font-weight: bold;
  margin: 20rpx 0;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin: 20rpx 0;
}

.tag {
  background-color: #f5f5f5;
  color: #666;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.footer {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 24rpx;
  margin-top: 20rpx;
}

.apply-btn {
  background-color: #1976d2;
  color: white;
  border: none;
  padding: 10rpx 30rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  cursor: pointer;
}

/* 父容器：确保选项水平排列 */
.radio-group {
  display: flex;         /* 横向排列选项 */
  gap: 60rpx;            /* 选项之间的间距 */
  padding: 10rpx 0;
}

/* 单个选项容器 */
.radio-item {
  cursor: pointer;       /* 手形指针 */
}

/* 核心：包裹单选框和文字的容器 */
.radio-inner {
  display: inline-flex;  /* 强制在同一行 */
  align-items: center;   /* 垂直居中对齐 */
  vertical-align: middle; /* 与其他元素基线对齐 */
}

/* 单选框样式 */
.radio-circle {
  width: 34rpx;
  height: 34rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;        /* 防止被压缩 */
}

/* 选中状态 */
.radio-circle.checked {
  border-color: #1976d2;
  background-color: #e3f2fd;
}

/* 选中圆点 */
.radio-dot {
  width: 18rpx;
  height: 18rpx;
  border-radius: 50%;
  background-color: #1976d2;
}

/* 文字样式 */
.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 16rpx;    /* 与单选框的间距 */
}
/* 输入框聚焦样式 */
input:focus,
textarea:focus {
  outline: none;
  border-color: #1976d;
}

/* 表单组样式 - 包含职位类型输入框整体布局 */
.form-group {
  margin-bottom: 30rpx;
}

/* 标签样式 - 职位类型文字标签 */
.label {
  display: block;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #555;
  font-size: 28rpx;
}

/* 选择器输入框样式 - 职位类型点击区域 */
.picker-input {
  display: flex;
  align-items: center;
  min-height: 76rpx;
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: white;
  cursor: pointer;
}

/* 选择器文字样式 - 职位类型显示文字 */
.picker-text {
  color: #333;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 错误提示样式 - 职位类型未选择时的错误文字 */
.error-text {
  color: #f44336;
  font-size: 24rpx;
  margin-top: 8rpx;
  display: block;
}

/* 错误边框样式 - 职位类型未选择时的红色边框 */
.error-border {
  border-color: #f44336 !important;
}

/* 输入框聚焦样式 - 职位类型选择框聚焦效果 */
.picker-input:focus {
  outline: none;
  border-color: #1976d2;
}
/* 去除 nut-textarea 的内边距 */
.nut-textarea {
  padding: 0 !important; /* 使用 !important 强制覆盖组件默认样式 */
}
</style>
